package groovy.lang.webobjects;

import groovy.lang.GroovyClassLoader;

import java.net.URL;
import java.net.URLClassLoader;

public class WOGroovyClassLoader extends GroovyClassLoader {
	private static GroovyClassLoader loader = null;
	
	public WOGroovyClassLoader() {
		this(Thread.currentThread().getContextClassLoader());
	}

	public WOGroovyClassLoader(ClassLoader parent) {
		super(parent);
		setShouldRecompile(true);
		
		if (parent instanceof URLClassLoader) {
			for (URL url : ((URLClassLoader)parent).getURLs()) {
				addURL(url);
			}
		}
	}
	
	public static Boolean reloadRequired() {
		for (Class<?> c : loader.getLoadedClasses()) {
			Class<?> class_;

			try {
				class_ = loader.loadClass(c.getName(), true, false, true);
				if (!class_.equals(c)) {
					return true;
				}
			} catch (Throwable e) { 
				e.printStackTrace();
			} 
		}
		return false;
	}
	
	public static void resetClassLoader() {
		loader = new WOGroovyClassLoader(loader.getParent());
	}
	
	public static ClassLoader getClassLoader() {
		if (loader == null) {
			loader = new WOGroovyClassLoader();
		}
		return loader;
	}

	public static void registerClassLoader() {
		Thread.currentThread().setContextClassLoader(getClassLoader());
	}
}
